<template>
  <div class="merchant-management">
    <!-- 商家信息展示与编辑 -->
    <div class="merchant-card">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>商家信息管理</span>
            <el-button
                v-if="!isEditing"
                type="primary"
                size="small"
                @click="startEditing"
            >
              编辑信息
            </el-button>
          </div>
        </template>

        <!-- 查看模式 -->
        <div v-if="!isEditing" class="info-view">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="商家名称">{{ merchantInfo.name || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ merchantInfo.address || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="经度设置">{{ merchantInfo.longitude || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="纬度设置">{{ merchantInfo.latitude || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ merchantInfo.contactPhone || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="营业时间">{{ merchantInfo.businessHours || '暂未设置' }}</el-descriptions-item>
            <el-descriptions-item label="商家描述">{{ merchantInfo.description || '暂未设置' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-form">
          <el-form
              ref="formRef"
              :model="editForm"
              label-width="100px"
              label-position="top"
              :rules="formRules"
          >
            <el-form-item label="商家名称" prop="name" required>
              <el-input v-model="editForm.name" placeholder="请输入商家名称" />
            </el-form-item>

            <el-form-item label="详细地址" prop="address" required>
              <el-input v-model="editForm.address" placeholder="请输入详细地址" />
            </el-form-item>
            <!--增加经纬度-->
            <el-form-item label="经度设置" prop="longitude" required>
              <el-input-number
                  v-model="editForm.longitude"
                  :precision="2"
                  :step="0.01"
                  :min="CHINA_BOUNDS.minLng"
                  :max="CHINA_BOUNDS.maxLng"
                  placeholder="请输入经度"
              />
            </el-form-item>
            <el-form-item label="纬度设置" prop="latitude" required>
              <el-input-number
                  v-model="editForm.latitude"
                  :precision="2"
                  :step="0.01"
                  :min="CHINA_BOUNDS.minLat"
                  :max="CHINA_BOUNDS.maxLat"
                  placeholder="请输入纬度"
              />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="editForm.businessHours" placeholder="例: 09:00-22:00" />
            </el-form-item>

            <el-form-item label="商家描述" prop="description">
              <el-input
                  v-model="editForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入商家描述"
              />
            </el-form-item>

            <div class="form-actions">
              <el-button @click="cancelEditing">取消</el-button>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </div>
          </el-form>
        </div>
      </el-card>
    </div>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import request from "@/utils/request";
// 中国经纬度大致范围（可根据需要调整）
const CHINA_BOUNDS = {
  minLng: 73.66,   // 最西端
  maxLng: 135.05,  // 最东端
  minLat: 3.86,    // 最南端
  maxLat: 53.55    // 最北端
}
// 状态管理


const editForm = ref({})
const isEditing = ref(false)
const formRef = ref(null)

// 获取当前商家ID
const getMerchantId = () => {
  return localStorage.getItem('id')
}

const merchantInfo = ref({
  id: null,
  merchantId:getMerchantId(),
  name: '',
  address: '',
  longitude: null,
  latitude: null,
  contactPhone:null,
  businessHours: null,
  description: null,
  logoUrl: null,
})

// 获取商家信息
const fetchMerchantInfo = async () => {
  try {
    const merchantId = getMerchantId()
    if (!merchantId) {
      ElMessage.warning('未找到商家ID')
      return
    }
    const response = await request.get('/api/merchant/getMerchantInfo')

    if (response.data) {
      merchantInfo.value = response.data
    }
    console.log('商家信息:', merchantInfo.value)
  } catch (error) {
    ElMessage.error('获取商家信息失败')
    console.error(error)
  }
}

// 开始编辑
const startEditing = () => {
  editForm.value=merchantInfo.value
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
}

// 提交表单 增加或者修改
const submitForm = async () => {
  try {
    if (merchantInfo.value.id) { //更新数据
      // 更新商家信息
      const response = await request.post('api/merchant/update', editForm.value)
      if (response.data && response.code === 200) {
        ElMessage.success('商家信息更新成功')
        merchantInfo.value = editForm.value
        isEditing.value = false
      }
    } else {
      // 创建商家信息
      const response = await request.post('api/merchant/add', editForm.value)
      if (response.data && response.code === 200) {
        ElMessage.success('商家信息创建成功')
        merchantInfo.id = response.data.data
        merchantInfo.value =editForm.value
        isEditing.value = false
      }
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error(error)
  }
}

// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: '商家名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  businessHours: [{ required: true, message: '营业时间不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '商家描述不能为空', trigger: 'blur' }]
})

// 初始化加载
onMounted(() => {
  fetchMerchantInfo()
})
</script>

<style scoped>
.merchant-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-view {
  padding: 10px;
}

.edit-form {
  padding: 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.merchant-list {
  margin-top: 20px;
}
</style>
